using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using SqlSugar;
using SqlSugarEx.LambdaExtend;
using SqlSugarEx.Realization;

namespace SqlSugarEx
{
	public class SqlSugarClientEx : SqlSugarClient
	{
		private AdoProvider _adoProvider;

		public Func<SqlRowUpdatingEventArgs, string> RowUpdatingHandler { get; set; }

		public SqlSugarClientEx(ConnectionConfig config)
			: base(config)
		{
			List<SqlFuncExternal> sqlFuncServices = new DbMethodEx().LambdaExtend();
			config.ConfigureExternalServices.SqlFuncServices = sqlFuncServices;
		}

		public virtual ISugarQueryable<T> QueryableBind<T>()
		{
			base.Context.InitMappingInfo(typeof(T));
			return this.CreateQueryableEx<T>();
		}

		public virtual bool UpdateBind()
		{
			SqlServerProviderEx sqlServerProviderEx = this._adoProvider as SqlServerProviderEx;
			if (sqlServerProviderEx != null)
			{
				sqlServerProviderEx.RowUpdatingHandler = this.RowUpdatingHandler;
				return sqlServerProviderEx.UpdateBind();
			}
			return (this._adoProvider as SqliteProviderEx)?.UpdateBind() ?? (this._adoProvider as MySqlProviderEx)?.UpdateBind() ?? false;
		}

		protected ISugarQueryable<T> CreateQueryableEx<T>()
		{
			if (base.Context.CurrentConnectionConfig.DbType == DbType.SqlServer)
			{
				this._adoProvider = new SqlServerProviderEx
				{
					Context = base.Context
				};
			}
			else if (base.Context.CurrentConnectionConfig.DbType == DbType.Sqlite)
			{
				this._adoProvider = new SqliteProviderEx
				{
					Context = base.Context
				};
			}
			else
			{
				if (base.Context.CurrentConnectionConfig.DbType != 0)
				{
					throw new Exception("not support!");
				}
				this._adoProvider = new MySqlProviderEx
				{
					Context = base.Context
				};
			}
			ISugarQueryable<T> result = new QueryableProviderEx<T>(this._adoProvider);
			return base.Context.CreateQueryable(result);
		}
	}
}
